package com.caigou.modules.famous.ui.personal

import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.bus.BusKey
import com.caigou.comm.base.bus.LiveDataBus
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.screenCapture
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.ImageLoader
import com.caigou.comm.base.utils.MediaUtils
import com.caigou.comm.base.widget.BuyFlowerDialog
import com.caigou.comm.base.widget.RewardDialog
import com.caigou.modules.famous.R
import com.caigou.modules.famous.adpter.FamousPageAdapter
import com.caigou.modules.famous.bean.PersonalBean
import com.caigou.modules.famous.databinding.ActivityFamousPersonalBinding
import com.caigou.modules.famous.ui.personal.fragment.*
import com.caigou.modules.famous.viewmodel.PersonalViewModel
import com.caigou.modules.famous.widget.FamousTypeDialog
import com.google.android.material.tabs.TabLayoutMediator
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/10
 */
@Route(path = RouterPath.Famous.PAGE_PERSONAL)
@AndroidEntryPoint
class FamousPersonalActivity : BaseActivity() {

    lateinit var binding: ActivityFamousPersonalBinding

    private val personalViewModel: PersonalViewModel by viewModels()

    @JvmField
    @Autowired(name = AppConstants.FAMOUS_TYPE)
    var famousType: Int = 1

    @Autowired(name = AppConstants.USER_ID)
    lateinit var userId: String

    private val itemNames = mutableListOf(
        "特肖",
        "特围",
        "平特",
        "半数",
        "其他",
        "杀榜"
    )

    private val fragments = mutableListOf<Fragment>(
        PersonalTeXiaoFragment(),
        PersonalTeWeiFragment(),
        PersonalPingTeFragment(),
        PersonalBanShuFragment(),
        PersonalOtherFragment(),
        PersonalShaBangFragment(),
    )

    private val pagerAdapter: FamousPageAdapter by lazy {
        FamousPageAdapter(this)
    }

    private var rewardDialog: RewardDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFamousPersonalBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.personalLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        pagerAdapter.setList(fragments)
        binding.personalViewPager2.adapter = pagerAdapter
        binding.personalViewPager2.isUserInputEnabled = false
        TabLayoutMediator(binding.personalTabLayout, binding.personalViewPager2, true, true) { tab, position ->
            tab.text = itemNames[position]
        }.attach()
        binding.personalViewPager2.offscreenPageLimit = itemNames.size

        binding.personalTvTitle.run {
            text = if (famousType == 1) {
                "港彩名人堂"
            } else {
                "澳彩名人堂"
            }
            setOnClickListener {
                val dialog = FamousTypeDialog(this@FamousPersonalActivity, famousType)
                dialog.apply {
                    rgFamousType.setOnCheckedChangeListener { group, checkedId ->
                        famousType = when (checkedId) {
                            btnHkFamous.id -> 1
                            btnMacaoFamous.id -> 2
                            else -> 1
                        }
                        text = if (famousType == 1) {
                            "港彩名人堂"
                        } else {
                            "澳彩名人堂"
                        }
                        LiveDataBus.get().with(BusKey.FAMOUS_TYPE_CHANGE, Int::class.java).value = famousType
                        dismiss()
                    }
                    show()
                }
            }
        }

        binding.personalHeaderLayout.personalHeaderLlBoard.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Personal.PAGE_PERSONAL_BOARD)
                .withString(AppConstants.USER_ID, userId)
                .navigation()
        }

        binding.personalTvBack.setOnClickListener {
            finish()
        }

        binding.personalTvShare.setOnClickListener {
            val bitmap = binding.personalLlContainer.screenCapture()
            MediaUtils.saveBitmap(this, bitmap)
            showToast("截图已保存到系统相册")
        }

        LiveDataBus.get().with(BusKey.REFRESH_USER_INFO_FINISH, Any::class.java).observe(this) {
            rewardDialog?.apply {
                tvMoney.text = AppBackgroundInfo.instance.userBean!!.balance.toString()
                tvFlower.text = AppBackgroundInfo.instance.userBean!!.flower.toString()
            }
        }
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(personalViewModel.rewardLiveData, ::handleSetReward)
        observe(personalViewModel.buyFlowerLiveData, ::handleBuyFlower)
        observe(personalViewModel.followLiveData, ::handleSetFollow)
    }

    private fun handleSetReward(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("打赏用户异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }

    private fun handleBuyFlower(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("购买小红花异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                showToast(result.data!!)
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
            }
        }
    }

    private fun handleSetFollow(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("关注异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                result.data?.apply {
                    showToast(result.data!!)
                }
                LiveDataBus.get().with(BusKey.REFRESH_USER_INFO).value = Any()
                LiveDataBus.get().with(BusKey.FAMOUS_TYPE_CHANGE, Int::class.java).value = famousType
            }
        }
    }

    fun handleHeaderUI(bean: PersonalBean) {
        binding.personalHeaderLayout.apply {
            if (TextUtils.isEmpty(bean.headImg)) {
                personalHeaderIvAvatar.setImageResource(R.drawable.img_comm_avatar)
            } else {
                ImageLoader.loadCircle(this@FamousPersonalActivity, bean.headImg, personalHeaderIvAvatar)
            }
            ImageLoader.load(this@FamousPersonalActivity, bean.growthIcon, personalHeaderIvLv)

            personalHeaderTvDareType.text = bean.dareTypeName
            personalHeaderTvRecord.text = "${bean.count}对${bean.successCount}"
            personalHeaderTvAccuracy.text = "${bean.accuracy}%"
            personalHeaderTvSuccessNumConn.text = bean.successCountConn.toString()
            personalHeaderTvFailNumConn.text = bean.failCountConn.toString()
            personalHeaderTvSuccessNumNow.text = bean.successCountNow.toString()
            personalHeaderTvNickname.text = bean.nickName

            personalHeaderTvLikeNum.text = "${bean.nicePoint}获赞"
        }

        binding.personalFooterLayout.apply {
            if (bean.concern) {
                personalFooterBtnFollow.setBackgroundResource(R.drawable.comm_btn_white_gray2)
                personalFooterBtnFollow.setTextColor(Color.parseColor("#505050"))
                personalFooterBtnFollow.text = "已关注"
            } else {
                personalFooterBtnFollow.setBackgroundResource(R.drawable.comm_btn_orange)
                personalFooterBtnFollow.setTextColor(Color.parseColor("#FFFFFF"))
                personalFooterBtnFollow.text = "+关注"
            }
        }
    }

    fun handleFooterUI(bean: PersonalBean) {
        binding.personalFooterLayout.personalFooterLlContainer.visibility = if (userId == AppBackgroundInfo.instance.userBean!!.userId) {
            View.GONE
        } else {
            View.VISIBLE
        }

        binding.personalFooterLayout.personalFooterBtnFollow.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                personalViewModel.setFollow(AppBackgroundInfo.instance.userBean!!.userId, userId)
            } else {
                showToast("请您先登录")
            }
        }

        binding.personalFooterLayout.personalFooterLlReward.setOnClickListener {
            rewardDialog?.apply {
                dismiss()
                rewardDialog = null
            }
            rewardDialog = RewardDialog(this, bean.headImg, object : RewardDialog.IRewardClickCallback {
                override fun onChargeMoney() {
                    showToast("暂未开放，敬请期待")
                }

                override fun onChargeFlower() {
                    val dialog = BuyFlowerDialog(this@FamousPersonalActivity)
                    dialog.apply {
                        btnConfirm.setOnClickListener {
                            personalViewModel.buyFlower(AppBackgroundInfo.instance.userBean!!.userId, flowerNum)
                            dismiss()
                        }
                        show()
                    }
                }

                override fun onReward(type: Int, num: Int) {
                    personalViewModel.setReward(type, num, AppBackgroundInfo.instance.userBean!!.userId, userId)
                }

            })
            rewardDialog?.show()
        }

    }

}